import json
import datetime
import random

from django import http
# 提交订单
from django.db import transaction
from django.views import View
from home.models import House
from order.models import Order
from tenement_project.utils.response_code import RET


# 下单
class PlaceOrderView(View):
    @transaction.atomic
    def post(self, request):
        user = request.user
        if user.is_authenticated:
            data_dicts = json.loads(request.body.decode())
            start_date = datetime.datetime.strptime(data_dicts["start_date"], '%Y-%m-%d').date()
            end_date = datetime.datetime.strptime(data_dicts["end_date"], '%Y-%m-%d').date()
            house_id = data_dicts["house_id"]
            house = House.objects.get(id=house_id)
            # orders = Order.objects.all().values_list("house", "begin_date", "end_date")
            house_orders = house.order_set.all().values("begin_date", "end_date", "status")
            if start_date == end_date:
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "最少住一晚"})
            if not all([start_date, end_date, house_id]):
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "订单信息有误"})

            for time in house_orders:  # 判断是否有人预定 这段想了挺久
                if time["begin_date"] <= start_date <= time["end_date"]:
                    return http.JsonResponse({"errno": RET.DATAEXIST, "errmsg": "该时间段已有人预定"})
                if time["begin_date"] <= end_date <= time["end_date"]:
                    return http.JsonResponse({"errno": RET.DATAEXIST, "errmsg": "该时间段已有人预定"})
                if time["status"] in [0, 1, 2]:
                    return http.JsonResponse({"errno": RET.DATAEXIST, "errmsg": "该时间段已有人预定"})

            data_dict = {}
            day = (end_date - start_date).days
            # 加入订单所需信息  创建订单字典信息
            data_dict["user"] = user
            data_dict["house"] = house
            data_dict["begin_date"] = start_date
            data_dict["end_date"] = end_date
            data_dict["days"] = day
            data_dict["house_price"] = house.price
            data_dict["amount"] = house.price * day
            data_dict["status"] = Order.ORDER_STATUS["WAIT_ACCEPT"]  # 待接单状态 我的逻辑先支付再接单
            # data_dict["id"] = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S') + \
            #                   str(user.id) + str(house_id) + "%05d" % random.randint(0, 10000)
            sid = transaction.savepoint()
            try:
                # 创建订单
                order = Order.objects.create(**data_dict)
            except Exception as e:
                print(e)
                transaction.savepoint_rollback(sid)
                return http.JsonResponse({"errno": RET.DBERR, "errmsg": "下单失败，数据异常"})

            transaction.savepoint_commit(sid)
            return http.JsonResponse({"errno": RET.OK, "errmsg": "下单成功", "data": {"order_id": order.id}})
        else:
            context = {
                "errno": RET.SESSIONERR,
                "errmsg": "未登录"
            }
            return http.JsonResponse(context)

    def get(self, request):
        user = request.user
        if user.is_authenticated:
            role = request.GET.get("role")
            if role not in ["custom", "landlord"]:  # 判断信身份
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "身份信息有误"})
            user_houses = House.objects.filter(user_id=user.id).order_by("create_time")  # 当前登录用户所有的房源
            user_orders = Order.objects.filter(user_id=user.id)  # 当前登录用户下单的所有订单
            all_order_list = []
            if role == "landlord":
                for user_house in user_houses:  # 房东的房
                    all_order = user_house.order_set.all()
                    for order in all_order:
                        order_dict = {
                            "amount": order.amount,
                            "comment": order.comment,  # 房东的房子不显示评价
                            "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "days": order.days,
                            "end_date": order.end_date.strftime("%Y-%m-%d"),
                            "img_url": user_house.index_image_url,
                            "order_id": order.id,
                            "start_date": order.begin_date.strftime("%Y-%m-%d"),
                            "status": Order.ORDER_STATUS_ENUM[order.status],
                            "title": user_house.title
                        }
                        all_order_list.append(order_dict)  # 所有作为房东的单子
            if role == "custom":
                for user_order in user_orders:
                    order_house = user_order.house
                    house_dict = {
                        "amount": user_order.amount,
                        "comment": user_order.comment,
                        "ctime": user_order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "days": user_order.days,
                        "end_date": user_order.end_date.strftime("%Y-%m-%d"),
                        "img_url": order_house.index_image_url,
                        "order_id": user_order.id,
                        "start_date": user_order.begin_date.strftime("%Y-%m-%d"),
                        "status": Order.ORDER_STATUS_ENUM[user_order.status],
                        "title": order_house.title
                    }
                    all_order_list.append(house_dict)

            context = {
                "data": {
                    "orders": all_order_list,

                },
                "errmsg": "获取成功",
                "errno": RET.OK
            }
            return http.JsonResponse(context)
        else:
            context = {
                "errno": RET.SESSIONERR,
                "errmsg": "未登录"
            }
            return http.JsonResponse(context)


# 房东接单和拒单
class OrderStatusView(View):
    def put(self, request, order_id):
        user = request.user
        if user.is_authenticated:
            data_dict = json.loads(request.body.decode())
            action = data_dict.get("action")
            reason = data_dict.get("reason")

            if action not in ["accept", "reject"]:
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "订单信息有误"})
            try:
                order = Order.objects.get(id=order_id)
            except Exception as e:
                return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "订单号有误"})
            if action == "accept":
                order.status = Order.ORDER_STATUS["WAIT_COMMENT"]  # 忽略支付环节 接单 房东显示已结单，房客待评价
                order.house.order_count += 1  # 下单订单数+1
            else:
                order.status = Order.ORDER_STATUS["REJECTED"]  # 拒单
                order.comment = reason
            order.save()
            return http.JsonResponse({"errno": RET.OK, "errmsg": "操作成功"})
        else:
            context = {
                "errno": RET.SESSIONERR,
                "errmsg": "未登录"
            }
            return http.JsonResponse(context)


# 评论 要登陆 待会处理
class OrderCommentView(View):
    def put(self, request, order_id):
        data_dict = json.loads(request.body.decode())
        comment = data_dict.get("comment")
        if len(comment) == 0 or len(comment) >= 50:
            return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "评论内容不符合要求"})
        try:
            order = Order.objects.get(id=order_id)
        except Exception as e:
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "订单号有误"})
        order.comment = comment
        order.status = Order.ORDER_STATUS["COMPLETE"]
        order.save()
        return http.JsonResponse({"errno": RET.OK, "errmsg": "评论成功"})
